import { ref, reactive, onMounted, unref } from "vue";
import { post } from "@/utils/http";

// Http 组合式函数
export function useHttp(url, initialParams) {
    //初始： 数据列表、加载状态、数据总数、分页信息
    const dataList = ref([]);// 数据列表
    const loading = ref(false);// 加载状态
    const totals = ref(0);// 数据总数
    const pageInfo = reactive({
        page: 1,// 当前页码
        pageSize: 10,// 每页显示条数
    });

    // 加载数据的函数
    const loadData = async () => {
        loading.value = true;

        try {
            const response = await post(url, {...pageInfo,...unref(initialParams)});
            const data = response.data;// 返回数据
            dataList.value = data.list;// 返回数据列表
            totals.value = data.total; // 返回总数

        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            loading.value = false;
        }
    };

    // 在组件挂载时加载数据
    onMounted(() => {
        loadData();
    });
// 分页相关事件处理函数
    const handleSizeChange = (size) => {
        console.log("handleSizeChange");
        pageInfo.pageSize = size;
        loadData();
    };

    const handleCurrentChange = (page) => {
        console.log("handleCurrentChange");
        pageInfo.page = page;
        loadData();
    };

    const resetPagination = () => {
        pageInfo.page = 1;
        pageInfo.pageSize = 10; 
        loadData();
    };

    return {
        dataList,
        loading,
        loadData,
        totals,
        pageInfo,
        handleSizeChange,
        handleCurrentChange,
        resetPagination,
    };
}